import { getCameraTree } from '@/api/camera'
import { $getDeviceList, $getAllDeviceInMap } from '@/api/device'
import { $getAllServer } from '@/api/nvr'
import { buildTree } from '@/utils/tree'
import type { TreeNode, Device, StreamServer, MapDevice } from '@/types'

/**
 * 获取摄像头树形结构的公用函数
 * @returns Promise<{ treeData: TreeNode[], flvServerList: StreamServer[], allDeviceInMap: MapDevice[] }>
 */
export async function fetchCameraTree(): Promise<{
  treeData: TreeNode[]
  flvServerList: StreamServer[]
  allDeviceInMap: MapDevice[]
}> {
  try {
    // 并行获取所有需要的数据
    const [flvServerResponse, allDeviceInMapResponse, cameraTreeResponse] = await Promise.all([
      $getAllServer(),
      $getAllDeviceInMap(),
      getCameraTree()
    ])

    const flvServerList = flvServerResponse.data
    const allDeviceInMap = allDeviceInMapResponse.data
    const treeData = buildTree(cameraTreeResponse.data)

    return {
      treeData,
      flvServerList,
      allDeviceInMap
    }
  } catch (error) {
    console.error('获取摄像头树形结构失败:', error)
    throw error
  }
}

/**
 * 根据节点ID获取设备列表
 * @param nodeId 节点ID
 * @returns Promise<Device[]>
 */
export async function fetchDevicesByNodeId(nodeId: number): Promise<Device[]> {
  try {
    const response = await $getDeviceList(nodeId.toString())
    return response.data || []
  } catch (error) {
    console.error(`获取节点 ${nodeId} 的设备列表失败:`, error)
    return []
  }
}

/**
 * 为树形结构加载设备数据
 * @param treeData 树形结构数据
 * @returns Promise<TreeNode[]>
 */
export async function loadDevicesForTree(treeData: TreeNode[]): Promise<TreeNode[]> {
  const loadDevicesForNode = async (node: TreeNode): Promise<TreeNode> => {
    const nodeWithDevices = { ...node, isDirectory: true }
    
    // 加载该目录下的设备
    const devices = await fetchDevicesByNodeId(node.id)
    if (devices.length > 0) {
      nodeWithDevices.devices = devices
    }
    
    // 递归处理子目录
    if (node.children && node.children.length > 0) {
      nodeWithDevices.children = await Promise.all(
        node.children.map(loadDevicesForNode)
      )
    }
    
    return nodeWithDevices
  }

  return Promise.all(treeData.map(loadDevicesForNode))
}
